import { DoubleLeftOutlined, DoubleRightOutlined } from "@ant-design/icons"
import Link from "antd/es/typography/Link"
import { useMemo, useState } from "react"

import useApi from "@/api/dxn"
import { IGameReplay, IGameReplayData, IHandListItemResponse } from "@/api/dxn/type"
import GameReplay from "@/components/modals/gameReplay"
import { useLocale } from "@/locales"
import { getGameReplayDetail } from "@/utils/replay"

const GameReplayAction = ({
	index,
	gameReplayData = {
		totalRecord: 0,
		query: {
			pageNum: 1,
			pageSize: 100
		}
	},
	tableData
}: {
	index: number
	gameReplayData: IGameReplayData
	tableData: IHandListItemResponse[]
}) => {
	const { newFormat } = useLocale()
	const [curentIndex, setCurrentIndex] = useState(index)
	const [gameReplaySearch, setGameReplaySearch] = useState<IGameReplayData>(gameReplayData)
	const [gameReplayLoading, setGameReplayLoading] = useState(false)
	const [gameReplayVisible, setGameReplayVisible] = useState(false)
	const [handTableList, setHandTableList] = useState<IHandListItemResponse[]>([])
	const [handStatus, setHandStatus] = useState(0)
	const { getHandPageListBend, showGameReviewCardListBend, getGameReviewDeatailListBend, loading } = useApi()

	const currentGameReplayRecord = useMemo(() => {
		if (gameReplaySearch) {
			return (gameReplaySearch.query.pageNum - 1) * gameReplaySearch.query.pageSize + curentIndex
		}
		return 0
	}, [gameReplaySearch, curentIndex])

	const isHandlePrev = useMemo(() => {
		return gameReplayLoading || (gameReplaySearch && currentGameReplayRecord <= 1)
	}, [gameReplayLoading, currentGameReplayRecord, gameReplaySearch])

	const isHandleNext = useMemo(() => {
		return gameReplayLoading || (gameReplaySearch && currentGameReplayRecord >= gameReplaySearch.totalRecord)
	}, [gameReplayLoading, currentGameReplayRecord, gameReplaySearch])

	const defaultGameReplay = {
		replayDetail: {
			info: {
				handId: ""
			},
			handStatus: undefined
		},
		replayList: [],
		replayReqResult: ""
	}
	const [gameReplay, setGameReplay] = useState<IGameReplay>(defaultGameReplay)

	const getGameReplayDetailInfo = (row: IHandListItemResponse) => {
		setHandStatus(row?.handStatus)
		setGameReplay(pre => ({
			...pre,
			replayReqResult: ""
		}))

		if (row?.handStatus === 0 || !row?.tableId) {
			setGameReplay({
				replayDetail: {
					info: {
						handId: row?.handCode
					},
					handStatus: row?.handStatus
				},
				replayList: [],
				replayReqResult: newFormat("common.no_record")
			})
			setGameReplayLoading(false)
		} else {
			getGameReplayDetail({
				replayQuery: {
					tableId: row.tableId,
					roundNo: row.handNum
				},
				handStatus: handStatus,
				$api: {
					showGameReviewCardListBend,
					getGameReviewDeatailListBend
				}
			})
				.then(ret => {
					setGameReplay(pre => ({
						...pre,
						replayDetail: {
							...ret.replayDetail,
							info: {
								...ret.replayDetail.info,
								handId: row.handCode
							},
							handStatus: row.handStatus
						},
						replayList: ret.replayList
					}))
					setGameReplayLoading(false)
				})
				.catch((ret: { message: any }) => {
					setGameReplay(pre => ({
						...pre,
						replayReqResult: ret.message
					}))
					setGameReplayLoading(false)
				})
		}
	}
	const getHandPage = async () => {
		setHandTableList([])
		const [err, data] = await getHandPageListBend(gameReplaySearch?.query || {})

		if (err) {
			setGameReplay(defaultGameReplay)
			setGameReplayLoading(false)
			setGameReplay(pre => ({ ...pre, replayReqResult: newFormat("common.not_getting_data") }))
		}

		if (data?.record) {
			if (Array.isArray(data?.record)) {
				setHandTableList(data.record)
				getGameReplayDetailInfo(data.record[curentIndex - 1] || {})
			}
		}
	}

	const getHandTableList = async (isLoad = false) => {
		setGameReplayLoading(true)

		if (isLoad || handTableList.length <= 0) {
			getHandPage()
		} else {
			getGameReplayDetailInfo(handTableList[curentIndex - 1] || {})
		}
	}

	const handleFirstGameReplay = () => {
		setCurrentIndex(index)
		setGameReplaySearch({
			totalRecord: gameReplayData.totalRecord,
			query: { ...gameReplayData.query }
		})
		setGameReplayVisible(true)
		setGameReplayLoading(true)
		setGameReplay(() => defaultGameReplay)

		const handList = [...tableData]
		setHandTableList(handList)

		if (handList.length <= 0) {
			getHandPage()
		} else {
			getGameReplayDetailInfo(handList[curentIndex - 1] || {})
		}
	}

	const handlePrevGameReplay = () => {
		if (curentIndex <= 1) {
			setCurrentIndex(gameReplaySearch ? gameReplaySearch.query.pageSize : 0)
			setGameReplaySearch(pre => {
				return {
					...pre,
					query: {
						...pre?.query,
						pageNum: pre?.query?.pageNum - 1 || 0
					}
				}
			})

			getHandTableList(true)
		} else {
			setCurrentIndex(pre => --pre)
			getHandTableList(false)
		}
	}

	const handleNextGameReplay = () => {
		if (curentIndex >= gameReplaySearch.query.pageSize) {
			setCurrentIndex(1)
			setGameReplaySearch(pre => {
				return {
					...pre,
					query: {
						...pre?.query,
						pageNum: pre?.query?.pageNum + 1 || 0
					}
				}
			})
			getHandTableList(true)
		} else {
			setCurrentIndex(pre => ++pre)
			getHandTableList(false)
		}
	}

	return (
		<>
			<div className="text-link ml15" onClick={handleFirstGameReplay}>
				{newFormat("dxn.hand_review")}
			</div>
			{gameReplayVisible && (
				<GameReplay
					title={newFormat("dxn.hand_review")}
					open={gameReplayVisible}
					dialogLoading={loading || gameReplayLoading}
					replayDetail={gameReplay.replayDetail}
					replayList={gameReplay.replayList}
					replayReqResult={gameReplay.replayReqResult}
					onCancel={() => setGameReplayVisible(false)}
				>
					<div className="arrowStyel">
						<Link underline={false} disabled={isHandlePrev}>
							<span onClick={handlePrevGameReplay}>
								<DoubleLeftOutlined />
								{`${newFormat("common.button.previous")}`}
							</span>
						</Link>
						<span>
							{currentGameReplayRecord}/{gameReplayData.totalRecord}
						</span>
						<Link underline={false} disabled={isHandleNext}>
							<span onClick={handleNextGameReplay}>
								{`${newFormat("common.button.next")}`}
								<DoubleRightOutlined />
							</span>
						</Link>
					</div>
				</GameReplay>
			)}
		</>
	)
}

export default GameReplayAction
